package cn.mesmile.shiro.config;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author zb
 * @date 2021/2/19 22:59
 * @Description: 检查 强制退出的情况
 */
public class CustomForceLogoutFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>>> CustomForceLogoutFilter 进入到认证过滤");
        Session session = getSubject(request, response).getSession(false);

        if(session == null) {

            return false;

        }

        return session.getAttribute("SESSION_FORCE_LOGOUT_KEY") == null;

    }

    /**
     *   isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception
     *   当上面的方法返回 false 的时候 就会进入到  onAccessDenied(ServletRequest request, ServletResponse response) throws Exception 方法中
     */

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        System.out.println(">>>>>>>>>>>>>>>>>> CustomForceLogoutFilter 进入到拒绝访问中 ");
        try {
            /*强制退出*/
            Subject subject = getSubject(request, response);
            System.out.println("subject.getPrincipal() 退出 = " + subject.getPrincipal());
            subject.logout();

        } catch (Exception e) {/*忽略异常*/}

        String loginUrl = getLoginUrl() + (getLoginUrl().contains("?") ? "&" : "?") + "forceLogout=1";

        WebUtils.issueRedirect(request, response, loginUrl);

        return false;

    }

}
